package cn.laixueit.controller;

import cn.laixueit.crawlerutil.CrawlerUtil;
import cn.laixueit.mapper.BookMapper;
import cn.laixueit.pojo.Book;
import cn.laixueit.pojo.Chapter;
import cn.laixueit.service.BookService;
import cn.laixueit.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private ChapterService chapterService;

    // 查所有小说、根据书名查
    @RequestMapping("/findAll")
    public String findAll(String bookName, Model model){
        List<Book> bookList = bookService.findAll(bookName);
        model.addAttribute("bookList",bookList);
        return "tour";
    }

    // 查询所有章节
    @RequestMapping("/findByBookId")
    public String findById(int id,Model model){
        // 根据bookid查询所有章节
        List<Chapter> chapterList = chapterService.findByBookId(id);
        model.addAttribute("chapterList",chapterList);
        // 获取章节中的bookid查询bookName
        Integer bookId = chapterList.get(0).getBookId();
        Book book = bookService.findByBookId(bookId);
        model.addAttribute("book",book);
        return "tour";
    }

    @Autowired
    private RedisTemplate redisTemplate;

    // 根据章节id查内容
    @RequestMapping("/findByContent")
    public String findByContent(Integer id,Model model){

        Chapter chapter = chapterService.findById(id);
        model.addAttribute("chapter",chapter.getChapter());

        Book book = bookService.findByBookId(chapter.getBookId());
        model.addAttribute("book",book);

        // 先去缓存查章节内容
        String content = (String) redisTemplate.boundHashOps(book.getId()).get(id);
        if(content==null){
            content = CrawlerUtil.crawlerBookContent(chapter.getLinkUrl());
            redisTemplate.boundHashOps(book.getId()).put(id,content);
        }
        model.addAttribute("content",content);
        return "tour";
    }

    // 刷新数据库
    @RequestMapping("/flush")
    public void crawlerBookChapter(){
        List<Book> bookList = bookService.findAll(null);

        List<Map> mapList = null;
        for (Book book : bookList) {
            mapList = CrawlerUtil.getBookChapter(book.getLinkUrl());

            chapterService.add(mapList,book.getId());
        }
    }

}
